//
//  MGGradientLayerView.m
//  Mango
//
//  Created by 胡超 on 2021/1/15.
//  Copyright © 2021 胡超. All rights reserved.
//

#import "MGGradientLayerView.h"
#import "UIColor+Mango.h"

@implementation MGGradientLayerView

+ (Class)layerClass {
    return [CAGradientLayer class];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.gradientLayer.startPoint = CGPointZero;
        self.gradientLayer.endPoint = CGPointMake(0, 1);
    }
    return self;
}

- (CAGradientLayer *)gradientLayer {
    return (CAGradientLayer *)self.layer;
}

- (void)setColors:(NSArray *)colors {
    if (colors.count == 1) {
        CGColorRef cgColor = nil;
        id color = colors.firstObject;
        if ([color isKindOfClass:UIColor.class]) {
            cgColor = ((UIColor *)color).CGColor;
        } else if ([color isKindOfClass:NSString.class]) {
            cgColor = UIColor.Hex(color).CGColor;
        }
        self.gradientLayer.backgroundColor = cgColor;
    } else {
        NSArray *colorsArr = @[];
        for (id color in colors) {
            if ([color isKindOfClass:UIColor.class]) {
                colorsArr = [colorsArr arrayByAddingObject:(id)((UIColor *)color).CGColor];
            } else if ([color isKindOfClass:NSString.class]) {
                colorsArr = [colorsArr arrayByAddingObject:(id)UIColor.Hex(color).CGColor];
            }
        }
        self.gradientLayer.colors = colorsArr;
    }
}

- (void)setLocations:(NSArray *)locations {
    self.gradientLayer.locations = locations;
}

- (void)setStartPoint:(CGPoint)startPoint {
    self.gradientLayer.startPoint = startPoint;
}

- (void)setEndPoint:(CGPoint)endPoint {
    self.gradientLayer.endPoint = endPoint;
}

@end
